package com.ushine.web.component.authority.service;

import com.ushine.web.base.model.base.DataFilterMetaDataBO;
import com.ushine.web.component.authority.DataFilterTypeEnum;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.HexValue;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.EnumMap;
import java.util.function.BiFunction;

/**
 * @Author: yls
 * @Date 2022/2/9 16:50
 * @Description: 6种数据权限管理类
 * @Version 1.0
 **/
@Service
public class TemplateManagerServiceImpl {

    @Resource
    private TemplateSqlServiceImpl templateSqlService;

    private EnumMap<DataFilterTypeEnum, BiFunction<Expression, DataFilterMetaDataBO, Expression>> sqlFunctionMap = new EnumMap<>(DataFilterTypeEnum.class);

    @PostConstruct
    public void initTemplateManager() {
        //本人创建的数据
        sqlFunctionMap.put(DataFilterTypeEnum.SELF_CREATE,
                (expression, dataFilterMetaDataBO) -> templateSqlService.getSqlBySelfCreate(expression, dataFilterMetaDataBO));

        // 本人
        sqlFunctionMap.put(DataFilterTypeEnum.SELF,
                (expression, dataFilterMetaDataBO) -> templateSqlService.getSqlBySelf(expression, dataFilterMetaDataBO));

        // 全部
        sqlFunctionMap.put(DataFilterTypeEnum.ALL,
                (expression, dataFilterMetaDataBO) -> templateSqlService.getSqlByAll(expression, dataFilterMetaDataBO));

        // 自定义组织机构
        sqlFunctionMap.put(DataFilterTypeEnum.DEPT_SETS,
                (expression, dataFilterMetaDataBO) -> templateSqlService.getSqlByDeptSets(expression, dataFilterMetaDataBO));

        //本人所在组织机构
        sqlFunctionMap.put(DataFilterTypeEnum.DEPT,
                (expression, dataFilterMetaDataBO) -> templateSqlService.getSqlByDept(expression, dataFilterMetaDataBO));

        // 自定义sql
        sqlFunctionMap.put(DataFilterTypeEnum.DIY,
                (expression, dataFilterMetaDataBO) -> templateSqlService.getSqlByDiy(expression, dataFilterMetaDataBO));

    }

    /**
     * 功能描述:
     * 〈 具体的数据隔离权限实现逻辑 〉
     *
     * @param where                基础条件
     * @param dataFilterMetaDataBO 数据权限基础信息类
     * @return : net.sf.jsqlparser.expression.Expression
     * @author : yls
     * @date : 2022/2/9 17:27
     */
    public Expression getDataQueryExpression(Expression where, DataFilterMetaDataBO dataFilterMetaDataBO) {
        BiFunction<Expression, DataFilterMetaDataBO, Expression> expressionBiFunction = sqlFunctionMap.get(dataFilterMetaDataBO.getFilterType());
        if (expressionBiFunction != null) {
            return expressionBiFunction.apply(where, dataFilterMetaDataBO);
        }
        return new HexValue("1=1");
    }
}
